<template>
  <div class="product-detail">
    <div class="page-header">
      <div class="header-left">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        <h2>商品详情</h2>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleEdit">
          <el-icon><Edit /></el-icon>
          编辑商品
        </el-button>
        <el-button type="success" @click="handleTrace">
          <el-icon><Search /></el-icon>
          查看溯源
        </el-button>
      </div>
    </div>

    <div class="detail-content" v-loading="loading">
      <!-- 基本信息卡片 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <label>商品名称：</label>
              <span>{{ productInfo.name }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>商品编码：</label>
              <span>{{ productInfo.code }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>商品分类：</label>
              <span>{{ productInfo.categoryName }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <label>品牌：</label>
              <span>{{ productInfo.brand }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>规格：</label>
              <span>{{ productInfo.specification }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>单位：</label>
              <span>{{ productInfo.unit }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <label>零售价：</label>
              <span class="price">¥{{ productInfo.retailPrice }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>批发价：</label>
              <span class="price">¥{{ productInfo.wholesalePrice }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>成本价：</label>
              <span class="price">¥{{ productInfo.costPrice }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <div class="info-item">
              <label>商品描述：</label>
              <span>{{ productInfo.description }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 库存信息卡片 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <span>库存信息</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stock-item">
              <div class="stock-label">总库存</div>
              <div class="stock-value">{{ productInfo.totalStock }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stock-item">
              <div class="stock-label">可用库存</div>
              <div class="stock-value available">{{ productInfo.availableStock }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stock-item">
              <div class="stock-label">锁定库存</div>
              <div class="stock-value locked">{{ productInfo.lockedStock }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stock-item">
              <div class="stock-label">预警库存</div>
              <div class="stock-value warning">{{ productInfo.warningStock }}</div>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <label>供应商：</label>
              <span>{{ productInfo.supplierName }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>生产日期：</label>
              <span>{{ productInfo.productionDate }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>保质期：</label>
              <span>{{ productInfo.expiryDate }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 溯源信息卡片 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <span>溯源信息</span>
            <el-button type="primary" size="small" @click="refreshTraceInfo">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </template>
        
        <div class="trace-timeline">
          <el-timeline>
            <el-timeline-item
              v-for="(trace, index) in traceInfo"
              :key="index"
              :timestamp="trace.time"
              :type="trace.type"
            >
              <div class="trace-content">
                <h4>{{ trace.title }}</h4>
                <p>{{ trace.description }}</p>
                <div class="trace-details" v-if="trace.details">
                  <el-tag v-for="detail in trace.details" :key="detail.key" size="small">
                    {{ detail.key }}: {{ detail.value }}
                  </el-tag>
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-card>

      <!-- 质量检测记录卡片 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <span>质量检测记录</span>
          </div>
        </template>
        
        <el-table :data="qualityRecords" style="width: 100%" border>
          <el-table-column prop="id" label="检测编号" width="120" />
          <el-table-column prop="testDate" label="检测日期" width="120" />
          <el-table-column prop="testType" label="检测类型" width="120" />
          <el-table-column prop="testResult" label="检测结果" width="100">
            <template #default="{ row }">
              <el-tag :type="row.testResult === '合格' ? 'success' : 'danger'">
                {{ row.testResult }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="inspector" label="检测员" width="100" />
          <el-table-column prop="remarks" label="备注" show-overflow-tooltip />
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="viewQualityDetail(row)">
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 销售记录卡片 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <span>销售记录</span>
          </div>
        </template>
        
        <el-table :data="salesRecords" style="width: 100%" border>
          <el-table-column prop="id" label="订单号" width="150" />
          <el-table-column prop="saleDate" label="销售日期" width="120" />
          <el-table-column prop="quantity" label="数量" width="80" />
          <el-table-column prop="unitPrice" label="单价" width="100">
            <template #default="{ row }">
              ¥{{ row.unitPrice }}
            </template>
          </el-table-column>
          <el-table-column prop="totalAmount" label="总金额" width="120">
            <template #default="{ row }">
              ¥{{ row.totalAmount }}
            </template>
          </el-table-column>
          <el-table-column prop="customer" label="客户" width="120" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Edit, Search, Refresh, ArrowLeft } from '@element-plus/icons-vue'

export default defineComponent({
  name: 'ProductDetail',
  components: {
    Edit,
    Search,
    Refresh,
    ArrowLeft
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const loading = ref(false)
    
    // 商品基本信息
    const productInfo = reactive({
      id: '',
      name: '有机苹果',
      code: 'P001',
      categoryName: '生鲜果蔬',
      brand: '绿色农场',
      specification: '500g/袋',
      unit: '袋',
      retailPrice: 15.80,
      wholesalePrice: 12.50,
      costPrice: 8.20,
      description: '新鲜有机苹果，无农药残留，口感脆甜，营养丰富。',
      totalStock: 1000,
      availableStock: 850,
      lockedStock: 50,
      warningStock: 100,
      supplierName: '绿色农场供应商',
      productionDate: '2024-01-10',
      expiryDate: '2024-02-10'
    })
    
    // 溯源信息
    const traceInfo = ref([
      {
        time: '2024-01-15 14:30:00',
        title: '商品上架',
        description: '商品已上架销售',
        type: 'success',
        details: [
          { key: '操作员', value: '张三' },
          { key: '位置', value: 'A区货架' }
        ]
      },
      {
        time: '2024-01-15 10:20:00',
        title: '质量检测',
        description: '通过质量检测，检测结果合格',
        type: 'success',
        details: [
          { key: '检测员', value: '李四' },
          { key: '检测项目', value: '农药残留、重金属' }
        ]
      },
      {
        time: '2024-01-14 16:45:00',
        title: '入库验收',
        description: '商品入库验收完成',
        type: 'primary',
        details: [
          { key: '验收员', value: '王五' },
          { key: '入库数量', value: '1000袋' }
        ]
      },
      {
        time: '2024-01-14 09:15:00',
        title: '运输配送',
        description: '商品从供应商仓库发出',
        type: 'info',
        details: [
          { key: '运输方式', value: '冷藏车' },
          { key: '预计到达', value: '2024-01-14 16:00' }
        ]
      },
      {
        time: '2024-01-13 08:30:00',
        title: '生产完成',
        description: '商品生产完成，准备发货',
        type: 'primary',
        details: [
          { key: '生产批次', value: '20240113-001' },
          { key: '生产数量', value: '1000袋' }
        ]
      }
    ])
    
    // 质量检测记录
    const qualityRecords = ref([
      {
        id: 'QC001',
        testDate: '2024-01-15',
        testType: '农药残留',
        testResult: '合格',
        inspector: '李四',
        remarks: '检测结果符合国家标准'
      },
      {
        id: 'QC002',
        testDate: '2024-01-15',
        testType: '重金属',
        testResult: '合格',
        inspector: '李四',
        remarks: '铅、汞、砷等重金属含量达标'
      },
      {
        id: 'QC003',
        testDate: '2024-01-14',
        testType: '外观检查',
        testResult: '合格',
        inspector: '王五',
        remarks: '外观完整，无破损'
      }
    ])
    
    // 销售记录
    const salesRecords = ref([
      {
        id: 'SO20240115001',
        saleDate: '2024-01-15',
        quantity: 5,
        unitPrice: 15.80,
        totalAmount: 79.00,
        customer: '零售客户',
        status: '已完成'
      },
      {
        id: 'SO20240115002',
        saleDate: '2024-01-15',
        quantity: 10,
        unitPrice: 15.80,
        totalAmount: 158.00,
        customer: '批发客户',
        status: '已完成'
      },
      {
        id: 'SO20240115003',
        saleDate: '2024-01-15',
        quantity: 3,
        unitPrice: 15.80,
        totalAmount: 47.40,
        customer: '零售客户',
        status: '处理中'
      }
    ])
    
    // 加载商品详情
    const loadProductDetail = async () => {
      loading.value = true
      try {
        // 模拟API请求
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 从路由参数获取商品ID
        const productId = route.params.id
        if (productId) {
          productInfo.id = productId
          // 这里应该调用API获取商品详情
        }
      } catch (error) {
        console.error('加载商品详情失败:', error)
        ElMessage.error('加载商品详情失败')
      } finally {
                  loading.value = true
      }
    }
    
    // 返回上一页
    const goBack = () => {
      router.go(-1)
    }
    
    // 编辑商品
    const handleEdit = () => {
      router.push(`/products/edit/${productInfo.id}`)
    }
    
    // 查看溯源
    const handleTrace = () => {
      router.push(`/traceability/detail/${productInfo.id}`)
    }
    
    // 刷新溯源信息
    const refreshTraceInfo = async () => {
      try {
        ElMessage.success('溯源信息已刷新')
        // 这里应该重新加载溯源信息
      } catch (error) {
        console.error('刷新溯源信息失败:', error)
        ElMessage.error('刷新溯源信息失败')
      }
    }
    
    // 查看质量检测详情
    const viewQualityDetail = (record) => {
      ElMessage.info(`查看检测记录: ${record.id}`)
      // 这里可以打开详情对话框或跳转到详情页面
    }
    
    // 获取状态类型
    const getStatusType = (status) => {
      const statusMap = {
        '已完成': 'success',
        '处理中': 'warning',
        '已取消': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    onMounted(() => {
      loadProductDetail()
    })
    
    return {
      loading,
      productInfo,
      traceInfo,
      qualityRecords,
      salesRecords,
      loadProductDetail,
      goBack,
      handleEdit,
      handleTrace,
      refreshTraceInfo,
      viewQualityDetail,
      getStatusType
    }
  }
})
</script>

<style scoped>
.product-detail {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-left h2 {
  margin: 0;
  color: #2563eb;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.info-item label {
  font-weight: bold;
  color: #666;
  min-width: 100px;
  margin-right: 10px;
}

.info-item .price {
  color: #e74c3c;
  font-weight: bold;
}

.stock-item {
  text-align: center;
  padding: 20px;
  border: 1px solid #e1e5e9;
  border-radius: 8px;
  background: #f8f9fa;
}

.stock-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.stock-value {
  font-size: 24px;
  font-weight: bold;
  color: #2563eb;
}

.stock-value.available {
  color: #27ae60;
}

.stock-value.locked {
  color: #f39c12;
}

.stock-value.warning {
  color: #e74c3c;
}

.trace-timeline {
  padding: 20px 0;
}

.trace-content h4 {
  margin: 0 0 5px 0;
  color: #2563eb;
}

:is(.trace-content p) {
  margin: 0 0 10px 0;
  color: #666;
}

.trace-details {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .header-right {
    width: 100%;
    display: flex;
    gap: 10px;
  }
  
  .stock-item {
    margin-bottom: 15px;
  }
}
</style> 